package com.concurrent.art.chapter10;

import java.util.concurrent.*;

/**
 * @Author: LIHU
 * @Date: 2019/11/12 21:47
 * @Description:
 */
public class FutureTaskTest {
    private final ConcurrentMap<Object, Future<String>> taskCache = new ConcurrentHashMap<Object, Future<String>>();

    public static void main(String[] args) throws Exception {

    }

    private String executionTask(final String taskName) throws Exception {
        while (true) {
            Future<String> future = taskCache.get(taskName);    //1.1,2.1
            if (null == future) {
                Callable<String> task = new Callable<String>() {
                    @Override
                    public String call() throws Exception {
                        return taskName;
                    }
                };
                //1.2创建人物
                FutureTask<String> futureTask = new FutureTask<>(task);
                future = taskCache.putIfAbsent(taskName, futureTask);    //1.3
                if (future == null) {
                    future = futureTask;
                    futureTask.run();                                   //1.4执行任务
                }
            }
            try {
                return future.get();                                    //1.5,2.2线程在此等待任务执行完成
            } catch (CancellationException e) {
                taskCache.remove(taskName, future);
            }

        }
    }
}
